package pogvue.gui.menus;

import org.jibble.epsgraphics.EpsGraphics2D;
import pogvue.datamodel.*;
import pogvue.io.*;
import pogvue.gui.*;
import pogvue.gui.event.*;
import pogvue.gui.hub.*;


import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.*;


public class FileMenu extends PanelMenu implements ActionListener {

    private JMenuItem            opentree;
    private JMenuItem            open;
    private JMenuItem            save;
    private JMenuItem            print;
    private JMenuItem            postscript;
    private JMenuItem            find;

    private CloseAction          close;
    private QuitAction           quit;
  public JFrame parent;
  public AlignSplitPanel asp;
    public FileMenu(JFrame parent,AlignSplitPanel asp,AlignViewport av,Controller c) {
	super("File",asp,av,c);
	this.parent = parent;
	this.asp    = asp;
    }


    protected void init() {

	save       = new JMenuItem("Save...");
	open       = new JMenuItem("Open...");
	opentree   = new JMenuItem("Open Tree...");
	
	print      = new JMenuItem("Print...");
	postscript = new JMenuItem("Postscript...");
	find       = new JMenuItem("Find...");

	save.setMnemonic(KeyEvent.VK_S);
	open.setMnemonic(KeyEvent.VK_O);
	opentree.setMnemonic(KeyEvent.VK_T);
	print.setMnemonic(KeyEvent.VK_P);
	find.setMnemonic(KeyEvent.VK_F);

	save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK));
	open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,ActionEvent.CTRL_MASK));
	opentree.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,ActionEvent.CTRL_MASK));
	print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,ActionEvent.CTRL_MASK));
	find.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,ActionEvent.CTRL_MASK));

	save.addActionListener(this);
	open.addActionListener(this);
	opentree.addActionListener(this);
	print.addActionListener(this);
	postscript.addActionListener(this);
	find.addActionListener(this);

	close        = new CloseAction("Close");
	quit         = new QuitAction("Quit");

	//	add(open);
	//add(opentree);
	add(save);
	addSeparator();
	add(print);
	add(postscript);
	addSeparator();
	add(find);
	addSeparator();
	add(close);
	add(quit);
    }

    public void actionPerformed(ActionEvent e) {
	if (e.getSource() == save) {

	  FileSavePanel fsp = new FileSavePanel(av);	   

	  JOptionPane.showMessageDialog(null,         // parent frame
				 fsp,                 // Message  - can be object
				 "Save File...",      // Frame title
				 JOptionPane.QUESTION_MESSAGE);


	  String file = fsp.getFile();

	  if (file.equals("")) {
	      return;
	  }

	  FileOutputStream fos = null;

	  try {
	    fos = new FileOutputStream(file);

	    AlignmentI al = av.getAlignment();

	    for (int i = 0; i < al.getHeight(); i++) {
	      SequenceI tmpseq = al.getSequenceAt(i);
          
	      if (tmpseq instanceof GFF) {
		System.out.println("Can't save sequence " + tmpseq.getName() + " : wrong type ");
	      } else if (tmpseq instanceof GappedSequence) {
		GappedFastaFile.write(fos,(Sequence)al.getSequenceAt(0),(GappedSequence)tmpseq);
	      } else {
		FastaFile.write(fos,tmpseq);
	      } 
	    }
	    fos.close();
	  } catch (IOException ex) {
	    System.out.println("Error saving file " + file);
	  }

	} else if (e.getSource() == print) {
	  AlignmentPanel ap2 = asp.getAlignmentPanel2();
	  AlignmentPanel ap1 = asp.getAlignmentPanel1();


	  System.out.println("Printing alignment");

	  PrinterJob printJob = PrinterJob.getPrinterJob();
	  PageFormat pf = printJob.pageDialog(printJob.defaultPage());
	    
	  printJob.setPrintable(asp,pf);	    
	    
	  if (printJob.printDialog()) {
	    try {
	      System.out.println("Printing");
	      printJob.print();
	    } catch (Exception ex) {
	      ex.printStackTrace();
	    }
	  }
	} else if (e.getSource() == postscript) {
	  JFileChooser fc = new JFileChooser();

	  int returnVal = fc.showSaveDialog(parent);
	    
	  File file = fc.getSelectedFile();

	  if (file != null) {
	      jibbleprint(file);
	  }
    } else if (e.getSource() == find) {
	JFrame jf = new JFrame("Find...");
	SearchPanel sp = new SearchPanel(av.getAlignment(),controller,av,jf);

	int width =  450;
	int height = 250;
	jf.getContentPane().add(sp);
	jf.setSize(width,height);
	
	 Dimension sd = Toolkit.getDefaultToolkit().getScreenSize();

	 jf.setLocation(sd.width / 2 - width / 2,
			sd.height / 2 - height / 2);

	 jf.show();

    } else {
	System.out.println("Unknown source " + e.getSource());
    }
}

  private void jibbleprint(File file) {
    try {
      AlignmentPanel ap1 = asp.getAlignmentPanel1();
      AlignmentPanel ap2 = asp.getAlignmentPanel2();
      FileOutputStream outputStream = new FileOutputStream(file);
	
      EpsGraphics2D g = new EpsGraphics2D("demo",outputStream,0,0,asp.size().width,asp.size().height);
      System.out.println("Painting postscript");
	
      asp.paint(g);
      System.out.println("Done");
	
      //ps.print(g.toString());
      //ps.close();
	
      System.out.println("Done");

      g.flush();
      g.close();

      //ap1.seqCanvas.buffer = true;
	
    } catch (Exception e2) {
	e2.printStackTrace();
    }
    
  }
    
    class InputAlignBoxAction extends JalAction {
	public InputAlignBoxAction(String name) {
	    super(name);
	}
	
	public void applyAction(ActionEvent evt) {
	    StatusEvent info =
		new StatusEvent(this,"Creating input textbox...",StatusEvent.INFO);
	    controller.handleStatusEvent(info);

	    String message = "Input alignment via text box";

	    //InputPopup ip = new InputPopup((JPanel)frame.getContentPane(),av,controller,message);

	}
    }


  class CloseAction extends JalAction {
    public CloseAction(String name) {
      super(name);
    }
    public void applyAction(ActionEvent evt) {
      //frame.dispose();
      System.exit(0);
    }
  }

  class QuitAction extends JalAction {
    public QuitAction(String name) {
      super(name);
    }
    public void applyAction(ActionEvent evt) {
	//if (! (frame.getAFParent() instanceof Applet)) {
	//    frame.getAlignViewport().saveGFFConfig();
//	    frame.dispose();
	//    System.exit(0);
	//} else {
	    //frame.dispose();
//	}
    }
  }

  class OpenTreeAction extends JalAction {
    public OpenTreeAction(String name) {
      super(name);
    }
    public void applyAction(ActionEvent evt) {
      controller.handleStatusEvent(new StatusEvent(this,"Creating file chooser...",StatusEvent.INFO));
    //  FileDialog fd = new FileDialog(frame,"Tree file");
    //  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    //  fd.setLocation((screenSize.width - fd.getSize().width) / 2,
	//	     (screenSize.height - fd.getSize().height) / 2);


      //fd.show();
      //String dir  = "";
      //String file = "";

     //if (fd.getDirectory() != null) {
     //   dir = fd.getDirectory();
     // }
     // if (fd.getFile() != null) {
     //   file = fd.getFile();
     // }
     // try {
	//  TreeFile tf = new TreeFile(fd.getDirectory() + "/" + fd.getFile(),"File");

	  //NJTree tree = tf.getTree();

	  //TreePanel treePanel = new TreePanel(frame,av,controller ,tree);
	  //TreeFrame treeFrame = new TreeFrame(frame,treePanel);

	  //treeFrame.setSize(500,500);


	  //screenSize = Toolkit.getDefaultToolkit().getScreenSize();

	  //treeFrame.setLocation((screenSize.width - treeFrame.getSize().width) / 2,
	//	      (screenSize.height - treeFrame.getSize().height) / 2);


	  //treeFrame.show();
      //} catch (IOException e) {
	//  System.out.println("Exception " + e);
      //}
      // controller.handleStatusEvent(new StatusEvent(this,"done",StatusEvent.INFO));
    }
  }



}
